// pages/activity/activityEnroll/activityEnroll.js
import {
  $wuxDialog
} from '../../../miniprogram_npm/wux-weapp/index';
import {
  obj2Param
} from '../../../utils/util';
import {
  applyActivity
} from '../../../api/activity';
import {
  pay
} from '../../../api/user';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId: 0,
    sexOptions: ['未知', '男', '女'],
    userList: [],
    price: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      activityId: Number(options.id),
      price: Number(options.price),
    })
    if (this.data.userList.length === 0) {
      wx.navigateTo({
        url: './form/index',
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.userList.length > 0) {
      this.setData({
        userList: this.data.userList,
      })
    }
  },

  /**
   * 编辑人员信息
   * @param {object} e 
   */
  handleEdit(e) {
    const tempId = Number(e.currentTarget.dataset.id);
    let obj;
    this.data.userList.forEach(item => {
      if (item.tempId === tempId) {
        obj = item;
      }
    })
    wx.navigateTo({
      url: './form/index?' + obj2Param(obj),
    })
  },

  /**
   * 删除人员信息
   * @param {object} e 
   */
  handleDelete(e) {
    const tempId = Number(e.currentTarget.dataset.id);
    const that = this;
    $wuxDialog().confirm({
      title: '警告',
      content: '确定删除此人吗',
      buttons: [{
        text: '取消',
      }, {
        text: '确定',
        type: 'primary',
        onTap(e) {
          that.setData({
            userList: that.data.userList.filter(item => item.tempId !== tempId)
          })
        }
      }],
    })
  },

  onPay() {
    const that = this;

    if (this.data.userList.length === 0) {
      wx.showToast({
        title: '请至少添加一组人员信息',
        icon: 'none'
      })
      return
    }

    $wuxDialog().confirm({
      title: '提示',
      content: `确认${that.data.price===0?'提交':'支付'}报名该活动吗？`,
      buttons: [{
        text: '取消',
      }, {
        text: that.data.price === 0 ? '提交' : '支付',
        type: 'primary',
        async onTap(e) {
          let res = await applyActivity({
            dtoList: that.data.userList,
            id: that.data.activityId,
          });

          if (that.data.price !== 0) {
            await pay(res.orderId);
          }

          wx.showToast({
            title: `${that.data.price===0?'提交':'支付'}成功`,
            icon: 'success',
            mask: true,
          })
          let timer = setTimeout(() => {
            clearTimeout(timer);
            wx.navigateBack({});
          }, 2000);
        }
      }],
    })

  },

})